package com.qf.controller;


import com.qf.entity.Role;
import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.utils.R;
import com.qf.vo.ResultVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @GetMapping("/login")
    public String login(){
        return "login";
    }

    //执行登入
    @RequestMapping("/login-ui")
    public String loginIn(String username, String password, HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //1.封装用户提交的用户名和密码
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //2.提交给安全框架
        Subject subject = SecurityUtils.getSubject();


        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            //用户名出错，报异常，跳转登入页面
            writer.print("<script>alert('用户名错误');location.href='/login.ftl'</script>");
            return null;
        } catch (IncorrectCredentialsException e) {
            //密码出错，报异常，跳转登入页面
            writer.print("<script>alert('密码错误');location.href='/login.ftl'</script>");
            return null;
        }
        User user = userService.findByUsername(username);
        Role role = userService.findRole(user.getUserId());
        user.setRoles(role);
        session.setAttribute("user",user);
        return "index";
    }



}
